package com.cangxuan.app.ui.user;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.*;
import android.widget.*;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.User;
import com.cangxuan.app.ui.BaseActivity;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;
import com.cangxuan.app.utils.ImageToBase64Utils;
import com.cangxuan.app.utils.UserUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: 陈青石、杨刚
 * Activity: 账号与安全页面
 * Layout: activity_account_security
 */
public class AccountSecurityActivity extends BaseActivity {


    public static class MyMainDialog extends Dialog {
        Context context;
        TextView textView;
        private ClickListenerInterface clickListenerInterface;

        interface ClickListenerInterface {
            void cancelListener();

            void sureListener();
        }

        public void setClickListener(ClickListenerInterface clickListenerInterface) {
            this.clickListenerInterface = clickListenerInterface;

        }

        public MyMainDialog(Context context, int style, TextView textView) {
            super(context, style);
            this.context = context;
            this.textView = textView;
        }

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            init();
        }

        public void init() {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            View view = layoutInflater.inflate(R.layout.activity_account_security_nickname, null);
            setContentView(view);
            Button cancel = view.findViewById(R.id.nickname_cancel);
            Button sure = view.findViewById(R.id.nickname_sure);
            input = findViewById(R.id.dialog_edit);
            Window dialogWindow = getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            DisplayMetrics d = context.getResources().getDisplayMetrics();
            lp.width = (int) (d.widthPixels * 0.8);
            dialogWindow.setAttributes(lp);
            input.setText(textView.getText());
            cancel.setOnClickListener(new ClickListener(textView));
            sure.setOnClickListener(new ClickListener(textView));
        }
        Handler handler = new Handler();
        EditText input;

        public class ClickListener implements View.OnClickListener {

            TextView view;

            public ClickListener(TextView view) {
                this.view = view;
            }

            @Override
            public void onClick(View v) {
                switch (v.getId()) {

                    case R.id.nickname_cancel:
                        clickListenerInterface.cancelListener();
                        break;
                    case R.id.nickname_sure:
                        clickListenerInterface.sureListener();
                        User user = UserUtils.getUser(context);
                        String nickname = input.getText().toString();
                        if (nickname.equals("")) {
                            Toast toast = Toast.makeText(context, "输入为空,请重新输入", Toast.LENGTH_SHORT);
                            toast.show();
                        } else {
                            ProgressDialog progressDialog = ProgressDialog.show(context, "", "修改昵称中请稍等...");
                            Thread thread = new Thread(() -> {
                                //构建header
                                Map<String, String> headers = new HashMap<>();
                                headers.put("Authorization", DeviceUtils.getDeviceID());
                                JSONObject jsonBody = new JSONObject();
                                jsonBody.put("nickname", nickname);
                                String jsonString = HttpUtils.post("/api/user/changeNickname", headers, jsonBody.toJSONString());
                                JSONObject jsonResponse = JSONObject.parseObject(jsonString);
                                if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                                    user.setNickname(nickname);
                                    UserUtils.setUser(context, user);   //将修改属性后的user对象保存到本地数据
                                    handler.post(() -> {
                                        progressDialog.dismiss();
                                        Log.i("message", "修改成功");
                                        Toast toast = Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT);
                                        toast.show();
                                        view.setText(nickname);  //更新UI

                                    });
                                }
                            });
                            thread.start();
                        }
                        break;
                }
            }
        }
    }

    LinearLayout accountAvatar;
    LinearLayout accountNickname;
    LinearLayout accountAddress;
    LinearLayout accountPayPassword;
    TextView setState;
    TextView txtName;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_security);
        setTitle("账号与安全");
        accountAvatar = findViewById(R.id.account_avatar);
        accountNickname = findViewById(R.id.account_nickname);
        accountAddress = findViewById(R.id.account_address);
        accountPayPassword = findViewById(R.id.account_paypassword);
        setState = findViewById(R.id.set_state);
        txtName = findViewById(R.id.txt_name);
        accountImg = findViewById(R.id.account_img);
        context = getApplicationContext();

        Permission();
        accountAvatar.setOnClickListener(view -> {
            setDialog();
        });
        accountNickname.setOnClickListener(view -> {
            createDialog();
        });
        accountAddress.setOnClickListener(view -> {
            Intent intent = new Intent(context, SetAddressActivity.class);
            startActivity(intent);
        });
        String facePath = "/data/data/" + getPackageName() + "/face" + "/head.jpg";
        accountImg.setImageURI(Uri.parse(facePath));
        Thread thread = new Thread(() -> {
            //构建header
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", DeviceUtils.getDeviceID());
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("facePath", ImageToBase64Utils.change(facePath));
            HttpUtils.post("/api/user/getFaceBase64", headers, jsonBody.toJSONString());
        });
        thread.start();
        //获取当前User
        User user = UserUtils.getUser(context);
        if (user.getNickname() == null) {
            txtName.setText("未设置");
        } else {
            txtName.setText(user.getNickname());
        }
        if (user.isHasSetTransPassword()) {
            setState.setText("已设置");
        } else {
            setState.setText("未设置");
        }
        ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == 2) {
                        //说明密碼修改成功
                        setState.setText("已设置");
                    }
                });
        accountPayPassword.setOnClickListener(view -> {
            Intent intent = new Intent(context, SetPayPasswordActivity.class);
            activityResultLauncher.launch(intent);
        });
    }

    private void createDialog() {
        MyMainDialog myMainDialog = new MyMainDialog(this, R.style.BottomDialog, txtName);
        myMainDialog.show();
        myMainDialog.setCanceledOnTouchOutside(false);
        myMainDialog.setClickListener(new MyMainDialog.ClickListenerInterface() {
            @Override
            public void cancelListener() {
                myMainDialog.dismiss();
            }

            @Override
            public void sureListener() {
                System.out.println("111");
                myMainDialog.dismiss();
            }
        });
    }
    ImageView accountImg;
    Uri imageUri;
    String path = Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "Camera" + File.separator + "Head.jpg";

    private void openCarema() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File file = new File(path);
        imageUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                try {
                    // 获取拍照后的图像文件并转换为Bitmap对象
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    // 根据ImageView的尺寸调整Bitmap对象的大小
                    int imageViewWidth = accountImg.getWidth();
                    int imageViewHeight = accountImg.getHeight();
                    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, imageViewWidth, imageViewHeight, true);
                    // 设置调整后的Bitmap对象为ImageView的图像
                    accountImg.setImageBitmap(resizedBitmap);
                    mCameraDialog.dismiss();
                    String headFile = "/data/data/" + getPackageName() + "/face";   //图片存放位置
                    File src = new File(path);
                    try {
                        InputStream inputStream = new FileInputStream(src);
                        byte[] bytes = new byte[inputStream.available()];   //图片文件的字节数组
                        inputStream.read(bytes);    //从源文件读取字节出来存放到bytes数组
                        inputStream.close();
                        File file = new File(headFile + "/head.jpg");
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(bytes, 0, bytes.length);
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    public void Permission() {
        //安卓7.0调用相机
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        //动态申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS,//联系人的权限
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};//读写SD卡权限
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
    }

    Dialog mCameraDialog;

    private void setDialog() {

        RelativeLayout root = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.activity_account_security_popmenu, null);
        mCameraDialog = new Dialog(this, R.style.BottomDialog);
        Button back = root.findViewById(R.id.btn4);
        back.setOnClickListener(view -> {
            mCameraDialog.dismiss();
        });
        Button shoot = root.findViewById(R.id.shoot);
        Button fromPhone = root.findViewById(R.id.from_phone);
        shoot.setOnClickListener(v -> openCarema());

        Log.i("拍摄的图片", "拍摄的图片的Base64编码是:" + ImageToBase64Utils.change(path));
        mCameraDialog.setContentView(root);
        mCameraDialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = mCameraDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setWindowAnimations(R.style.dialogWindowAnim);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        lp.width = (int) getResources().getDisplayMetrics().widthPixels;
        root.measure(0, 0);
        lp.height = root.getMeasuredHeight();
        lp.alpha = 9f;
        dialogWindow.setAttributes(lp);
        mCameraDialog.show();
    }
}
